import React, { useState, useRef, useEffect } from 'react'
import {
  Button,
  Modal,
  Progress,
  message,
  Card,
  Space,
  Typography,
  Tooltip,
} from 'antd'
import {
  PlayCircleOutlined,
  StopOutlined,
  PauseCircleOutlined,
  DownloadOutlined,
  VideoCameraOutlined,
  CloseOutlined,
} from '@ant-design/icons'
import * as rrweb from 'rrweb'
import rrwebPlayer, { RRwebPlayerOptions } from 'rrweb-player'
import './style.css'

const { Text } = Typography

// rrweb相关类型定义

type eventWithTime = {
  timestamp: number
  delay?: number
}

interface CustomEvent extends Event {
  detail?: unknown
  target: EventTarget | null
}

interface RecordingPanelProps {
  className?: string
}

console.log(rrwebPlayer)

const RecordingPanel: React.FC<RecordingPanelProps> = ({ className }) => {
  // 状态管理
  const [isRecording, setIsRecording] = useState(false)
  const [isPlaying, setIsPlaying] = useState(false)
  const [events, setEvents] = useState<eventWithTime[]>([])
  const [recordDuration, setRecordDuration] = useState(0)
  const [playProgress, setPlayProgress] = useState(0)
  const [isModalVisible, setIsModalVisible] = useState(false)
  const [isMinimized, setIsMinimized] = useState(false)

  // 引用
  const stopFnRef = useRef<(() => void) | null>(null)
  const replayerRef = useRef<rrwebPlayer | null>(null)
  const startTimeRef = useRef<number | null>(null)
  const recordTimerRef = useRef<NodeJS.Timeout | null>(null)
  const replayTargetRef = useRef<HTMLDivElement>(null)

  // 格式化时间显示
  const formatTime = (ms: number): string => {
    const seconds = Math.floor(ms / 1000)
    const minutes = Math.floor(seconds / 60)
    const remainingSeconds = seconds % 60
    return `${minutes.toString().padStart(2, '0')}:${remainingSeconds
      .toString()
      .padStart(2, '0')}`
  }

  // 开始录制
  const startRecording = async () => {
    if (isRecording) return

    try {
      // 检查rrweb是否可用
      if (typeof rrweb === 'undefined') {
        message.error('rrweb库未加载，请检查页面配置')
        return
      }

      // 清空之前的数据
      setEvents([])
      setRecordDuration(0)
      setPlayProgress(0)
      startTimeRef.current = Date.now()

      // 开始rrweb录制
      stopFnRef.current = rrweb.record({
        emit: (event: eventWithTime) => {
          setEvents((prev) => [...prev, event])
        },
        checkoutEveryNth: 100, // 每 100 个 event 重新制作快照
        recordCanvas: true, // 录制canvas
        inlineStylesheet: true, // 内联样式表
        inlineImages: true, // 内联图片为base64，避免blob URL问题
        // 定制的选项
        plugins: [
          rrweb.getRecordConsolePlugin({
            level: ['info', 'log', 'warn', 'error'],
            lengthThreshold: 10000,
            stringifyOptions: {
              stringLengthLimit: 1000,
              numOfKeysLimit: 100,
              depthOfLimit: 1,
            },
            logger: window.console,
          }),
        ],
      }) as unknown as null

      setIsRecording(true)
      message.success('开始录制')
      console.log('开始录制用户操作')

      // 启动计时器
      recordTimerRef.current = setInterval(() => {
        if (startTimeRef.current) {
          const duration = Date.now() - startTimeRef.current
          setRecordDuration(duration)
        }
      }, 1000)

      // 添加自定义事件监听
      addCustomEventListeners()
    } catch (error) {
      console.error('录制启动失败:', error)
      message.error('录制启动失败: ' + (error as Error).message)
    }
  }

  // 停止录制
  const stopRecording = () => {
    if (!isRecording) return

    try {
      // 停止rrweb录制
      if (stopFnRef.current) {
        stopFnRef.current()
        stopFnRef.current = null
      }

      // 停止计时器
      if (recordTimerRef.current) {
        clearInterval(recordTimerRef.current)
        recordTimerRef.current = null
      }

      // 重置录制状态
      setIsRecording(false)
      startTimeRef.current = null

      message.success(`录制已停止，共记录 ${events.length} 个事件`)
      console.log('录制已停止，共记录', events.length, '个事件')
    } catch (error) {
      console.error('停止录制失败:', error)
      message.error('停止录制失败')
      // 即使出错也要重置状态
      setIsRecording(false)
      startTimeRef.current = null
    }
  }

  // 开始回放
  const startReplay = async () => {
    if (events.length === 0) {
      message.warning('没有录制数据，请先进行录制')
      return
    }

    if (isPlaying) return

    // 如果正在录制，先停止录制
    if (isRecording) {
      stopRecording()
      // 等待录制完全停止
      await new Promise((resolve) => setTimeout(resolve, 100))
    }

    try {
      setIsPlaying(true)
      setIsModalVisible(true)
      setPlayProgress(0)

      // 等待Modal渲染完成
      setTimeout(async () => {
        if (!replayTargetRef.current) {
          message.error('回放容器未找到')
          setIsPlaying(false)
          return
        }
        // 清空回放容器
        replayTargetRef.current.innerHTML = ''

        // 创建rrwebPlayer实例
        replayerRef.current = new rrwebPlayer({
          target: replayTargetRef.current,
          props: {
            events: events as RRwebPlayerOptions['props']['events'],
            width: 820,
            height: 600,
            plugins: [
              rrweb.getReplayConsolePlugin({
                level: ['info', 'log', 'warn', 'error'],
              }),
            ],
          },
        })

        message.success('开始回放')
        console.log('rrwebPlayer已创建，事件数量:', events.length)

        // 模拟进度更新
        const totalDuration = recordDuration
        const progressInterval = setInterval(() => {
          setPlayProgress((prev) => {
            const newProgress = prev + 100 / (totalDuration / 1000)
            if (newProgress >= 100) {
              clearInterval(progressInterval)
              setIsPlaying(false)
              message.success('回放完成')
              return 100
            }
            return newProgress
          })
        }, 1000)
      }, 300)
    } catch (error) {
      console.error('回放启动失败:', error)
      message.error('回放启动失败: ' + (error as Error).message)
      setIsPlaying(false)
    }
  }

  // 暂停回放
  const pauseReplay = () => {
    setIsPlaying(false)
    message.info('回放已暂停')
  }

  // 下载录制数据
  const downloadData = () => {
    if (events.length === 0) {
      message.warning('没有录制数据可下载')
      return
    }

    try {
      const dataStr = JSON.stringify(
        {
          events: events,
          recordDuration: recordDuration,
          timestamp: Date.now(),
          userAgent: navigator.userAgent,
          url: window.location.href,
        },
        null,
        2
      )

      const dataBlob = new Blob([dataStr], { type: 'application/json' })
      const url = URL.createObjectURL(dataBlob)
      const link = document.createElement('a')
      link.href = url
      link.download = `recording-${new Date()
        .toISOString()
        .slice(0, 19)
        .replace(/:/g, '-')}.json`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      message.success('录制数据已下载')
    } catch (error) {
      console.error('下载失败:', error)
      message.error('下载失败')
    }
  }

  // 添加自定义事件监听器
  const addCustomEventListeners = () => {
    const eventTypes = [
      'modalOpened',
      'modalClosed',
      'popupOpened',
      'popupClosed',
    ]

    eventTypes.forEach((eventType) => {
      document.addEventListener(eventType, (e: Event) => {
        const customEvent = e as CustomEvent
        console.log(`自定义事件: ${eventType}`, customEvent.detail)
        if (customEvent.target && customEvent.target instanceof Element) {
          triggerManualMutation(customEvent.target)
        }
      })
    })
  }

  // 触发手动DOM变化
  const triggerManualMutation = (element: Element) => {
    if (element) {
      const tempAttr = 'data-rrweb-' + Date.now()
      element.setAttribute(tempAttr, 'trigger')
      setTimeout(() => {
        element.removeAttribute(tempAttr)
      }, 10)
    }
  }

  // 清理资源
  useEffect(() => {
    return () => {
      // 清理录制相关资源
      if (recordTimerRef.current) {
        clearInterval(recordTimerRef.current)
        recordTimerRef.current = null
      }
      if (stopFnRef.current) {
        stopFnRef.current()
        stopFnRef.current = null
      }
      // 清理回放器实例
      if (replayerRef.current) {
        try {
          // rrwebPlayer继承自SvelteComponent，使用$destroy方法
          ;(replayerRef.current as any).$destroy()
        } catch (e) {
          console.warn('回放器销毁失败:', e)
        }
        replayerRef.current = null
      }
      // 重置所有状态
      setIsRecording(false)
      setIsPlaying(false)
      startTimeRef.current = null
    }
  }, [])

  // 渲染浮动面板
  const renderFloatingPanel = () => {
    if (isMinimized) {
      return (
        <div
          className='recording-panel-minimized'
          style={{
            position: 'fixed',
            bottom: '20px',
            right: '20px',
            zIndex: 9999,
            background: '#fff',
            borderRadius: '50%',
            width: '60px',
            height: '60px',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
            cursor: 'pointer',
            border: isRecording ? '3px solid #ff4d4f' : '1px solid #d9d9d9',
          }}
          onClick={() => setIsMinimized(false)}
        >
          <VideoCameraOutlined
            style={{
              fontSize: '24px',
              color: isRecording ? '#ff4d4f' : '#1890ff',
            }}
          />
        </div>
      )
    }

    return (
      <Card
        className={`recording-panel ${className || ''}`}
        style={{
          position: 'fixed',
          bottom: '20px',
          right: '20px',
          width: '320px',
          zIndex: 9999,
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)',
        }}
        title={
          <div
            style={{
              display: 'flex',
              justifyContent: 'space-between',
              alignItems: 'center',
            }}
          >
            <span>🎬 录制面板</span>
            <Space>
              <Tooltip title='最小化'>
                <Button
                  type='text'
                  size='small'
                  icon={<CloseOutlined />}
                  onClick={() => setIsMinimized(true)}
                />
              </Tooltip>
            </Space>
          </div>
        }
        size='small'
      >
        <Space direction='vertical' style={{ width: '100%' }}>
          {/* 录制状态 */}
          <div style={{ textAlign: 'center' }}>
            {isRecording ? (
              <Text type='danger'>
                🔴 录制中... {formatTime(recordDuration)}
              </Text>
            ) : (
              <Text>准备就绪 - 共 {events.length} 个事件</Text>
            )}
          </div>

          {/* 控制按钮 */}
          <Space wrap style={{ width: '100%', justifyContent: 'center' }}>
            <Tooltip title='开始录制'>
              <Button
                type='primary'
                icon={<VideoCameraOutlined />}
                onClick={startRecording}
                disabled={isRecording}
                size='small'
              >
                录制
              </Button>
            </Tooltip>

            <Tooltip title='停止录制'>
              <Button
                danger
                icon={<StopOutlined />}
                onClick={stopRecording}
                disabled={!isRecording}
                size='small'
              >
                停止
              </Button>
            </Tooltip>

            <Tooltip title='回放'>
              <Button
                icon={<PlayCircleOutlined />}
                onClick={startReplay}
                disabled={events.length === 0 || isRecording}
                size='small'
              >
                回放
              </Button>
            </Tooltip>

            <Tooltip title='下载数据'>
              <Button
                icon={<DownloadOutlined />}
                onClick={downloadData}
                disabled={events.length === 0}
                size='small'
              >
                下载
              </Button>
            </Tooltip>
          </Space>
        </Space>
      </Card>
    )
  }

  return (
    <>
      {/* 全局样式修复 */}
      <style>
        {`
           .recording-replay-modal .rr-player {
             font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif !important;
             border: 1px solid #d9d9d9 !important;
             border-radius: 6px !important;
             overflow: hidden !important;
           }
           .recording-replay-modal .rr-player * {
             box-sizing: border-box !important;
           }
           .recording-replay-modal .rr-player .rr-controller {
             font-size: 14px !important;
             color: #333 !important;
             background: #fff !important;
             border-top: 1px solid #d9d9d9 !important;
           }
           .recording-replay-modal .rr-player .rr-controller button {
             font-size: 12px !important;
             color: #333 !important;
             cursor: pointer !important;
             background: #fff !important;
             border: 1px solid #d9d9d9 !important;
             border-radius: 4px !important;
             margin: 0 4px !important;
             padding: 4px 8px !important;
           }
           .recording-replay-modal .rr-player .rr-controller button:hover {
             background: #f5f5f5 !important;
             border-color: #40a9ff !important;
           }
           .recording-replay-modal .rr-player .rr-controller button:disabled {
             opacity: 0.6 !important;
             cursor: not-allowed !important;
             background: #f5f5f5 !important;
           }
           .recording-replay-modal .rr-player .rr-controller select {
             border: 1px solid #d9d9d9 !important;
             border-radius: 4px !important;
             padding: 2px 4px !important;
             background: #fff !important;
           }
           .recording-replay-modal .rr-player .rr-timeline {
             background: #f5f5f5 !important;
           }
           .recording-replay-modal .rr-player .rr-progress {
             background: #1890ff !important;
           }
         `}
      </style>
      {renderFloatingPanel()}

      {/* 回放弹框 */}
      <Modal
        title='录制回放'
        open={isModalVisible}
        onCancel={() => {
          // 清理回放器实例
          if (replayerRef.current) {
            try {
              // rrwebPlayer继承自SvelteComponent，使用$destroy方法
              ;(replayerRef.current as any).$destroy()
            } catch (e) {
              console.warn('回放器销毁失败:', e)
            }
            replayerRef.current = null
          }
          setIsModalVisible(false)
          setIsPlaying(false)
          setPlayProgress(0)
        }}
        footer={[
          <Button
            key='close'
            onClick={() => {
              // 清理回放器实例
              if (replayerRef.current) {
                try {
                  // rrwebPlayer继承自SvelteComponent，使用$destroy方法
                  ;(replayerRef.current as any).$destroy()
                } catch (e) {
                  console.warn('回放器销毁失败:', e)
                }
                replayerRef.current = null
              }
              setIsModalVisible(false)
              setIsPlaying(false)
              setPlayProgress(0)
            }}
          >
            关闭
          </Button>,
          <Button
            key='pause'
            icon={<PauseCircleOutlined />}
            onClick={pauseReplay}
            disabled={!isPlaying}
          >
            暂停
          </Button>,
        ]}
        width={900}
        centered
        destroyOnClose
        className='recording-replay-modal'
        bodyStyle={{ padding: '16px' }}
      >
        <div style={{ marginBottom: '16px' }}>
          <Progress
            percent={Math.round(playProgress)}
            status={isPlaying ? 'active' : 'normal'}
            showInfo={true}
          />
          <div style={{ textAlign: 'center', marginTop: '8px' }}>
            <Text type='secondary'>
              {isPlaying ? '正在回放...' : '回放已暂停'} | 总时长:{' '}
              {formatTime(recordDuration)}
            </Text>
          </div>
        </div>

        <div
          ref={replayTargetRef}
          style={{
            width: '100%',
            height: '600px',
            border: '1px solid #d9d9d9',
            borderRadius: '6px',
            background: '#f5f5f5',
          }}
        />
      </Modal>
    </>
  )
}

// 扩展Window接口以支持rrweb
declare global {
  interface Window {
    rrweb: typeof rrweb
    rrwebPlayer: typeof rrwebPlayer
  }
}

export default RecordingPanel
